import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import './transaction_list_page.dart';
import './withdraw_page.dart';
import './income_stats_page.dart';

class WalletPage extends StatefulWidget {
  const WalletPage({super.key});

  @override
  State<WalletPage> createState() => _WalletPageState();
}

class _WalletPageState extends State<WalletPage> {
  final RefreshController _refreshController = RefreshController();
  
  // 模拟钱包数据
  double _balance = 2580.50;
  double _todayIncome = 320.00;
  double _monthIncome = 4800.00;

  // 模拟交易记录
  final List<Map<String, dynamic>> _transactions = [
    {
      'id': '1',
      'type': 'income',
      'amount': 320.00,
      'title': '搬家服务收入',
      'orderId': 'DD20240320001',
      'time': '2024-03-20 15:30',
      'status': 'completed',
    },
    {
      'id': '2',
      'type': 'withdraw',
      'amount': 1000.00,
      'title': '提现',
      'time': '2024-03-19 14:20',
      'status': 'completed',
    },
    {
      'id': '3',
      'type': 'income',
      'amount': 280.00,
      'title': '搬家服务收入',
      'orderId': 'DD20240319001',
      'time': '2024-03-19 10:15',
      'status': 'completed',
    },
  ];

  @override
  void dispose() {
    _refreshController.dispose();
    super.dispose();
  }

  /// 刷新钱包数据
  Future<void> _onRefresh() async {
    try {
      await Future.delayed(const Duration(seconds: 1));
      // TODO: 实际项目中这里应该调用API刷新数据
      _refreshController.refreshCompleted();
    } catch (e) {
      _refreshController.refreshFailed();
    }
  }

  /// 加载更多交易记录
  Future<void> _onLoading() async {
    try {
      await Future.delayed(const Duration(seconds: 1));
      setState(() {
        _transactions.addAll([
          {
            'id': DateTime.now().toString(),
            'type': 'income',
            'amount': 260.00,
            'title': '搬家服务收入',
            'orderId': 'DD20240318001',
            'time': '2024-03-18 16:40',
            'status': 'completed',
          }
        ]);
      });
      _refreshController.loadComplete();
    } catch (e) {
      _refreshController.loadFailed();
    }
  }

  /// 提现操作
  Future<void> _withdraw() async {
    final amount = await Navigator.push<double>(
      context,
      MaterialPageRoute(
        builder: (context) => WithdrawPage(balance: _balance),
      ),
    );

    if (amount != null && mounted) {
      // 提现成功，更新余额
      setState(() {
        _balance -= amount;
        // 添加提现记录
        _transactions.insert(0, {
          'id': DateTime.now().toString(),
          'type': 'withdraw',
          'amount': amount,
          'title': '提现',
          'time': DateTime.now().toString().substring(11, 16),
          'status': 'completed',
        });
      });

      // 显示提现成功提示
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('提现成功，金额：¥${amount.toStringAsFixed(2)}'),
          behavior: SnackBarBehavior.floating,
        ),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFF5F5F5),
      appBar: AppBar(
        title: const Text('我的钱包'),
        centerTitle: true,
        backgroundColor: Colors.white,
        elevation: 0,
        actions: [
          // 添加收益统计入口
          IconButton(
            onPressed: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => const IncomeStatsPage(),
                ),
              );
            },
            icon: const Icon(Icons.bar_chart),
          ),
        ],
      ),
      body: SmartRefresher(
        controller: _refreshController,
        enablePullDown: true,
        enablePullUp: _transactions.length >= 10,
        header: ClassicHeader(
          refreshStyle: RefreshStyle.Follow,
          idleText: '下拉刷新',
          refreshingText: '加载中...',
          completeText: '刷新成功',
          failedText: '刷新失败',
          releaseText: '松开刷新',
          height: 44,
          spacing: 8,
          iconPos: IconPosition.left,
          textStyle: TextStyle(color: Colors.grey[600], fontSize: 12),
          refreshingIcon: SizedBox(
            width: 16,
            height: 16,
            child: CircularProgressIndicator(
              strokeWidth: 2,
              valueColor: AlwaysStoppedAnimation<Color>(Colors.grey[600]!),
            ),
          ),
        ),
        footer: ClassicFooter(
          loadStyle: LoadStyle.ShowAlways,
          idleText: '上拉加载更多',
          loadingText: '加载中...',
          noDataText: '没有更多数据',
          failedText: '加载失败',
          canLoadingText: '松开加载更多',
          height: 44,
          spacing: 8,
          iconPos: IconPosition.left,
          textStyle: TextStyle(color: Colors.grey[600], fontSize: 12),
          loadingIcon: SizedBox(
            width: 16,
            height: 16,
            child: CircularProgressIndicator(
              strokeWidth: 2,
              valueColor: AlwaysStoppedAnimation<Color>(Colors.grey[600]!),
            ),
          ),
        ),
        onRefresh: _onRefresh,
        onLoading: _onLoading,
        child: CustomScrollView(
          slivers: [
            // 余额卡片
            SliverToBoxAdapter(
              child: Container(
                margin: const EdgeInsets.all(16),
                padding: const EdgeInsets.all(20),
                decoration: BoxDecoration(
                  gradient: const LinearGradient(
                    begin: Alignment.topLeft,
                    end: Alignment.bottomRight,
                    colors: [Color(0xFFFF7043), Color(0xFFFF5722)],
                  ),
                  borderRadius: BorderRadius.circular(12),
                  boxShadow: [
                    BoxShadow(
                      color: const Color(0xFFFF5722).withOpacity(0.3),
                      blurRadius: 8,
                      offset: const Offset(0, 4),
                    ),
                  ],
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Text(
                      '账户余额',
                      style: TextStyle(
                        fontSize: 14,
                        color: Colors.white70,
                      ),
                    ),
                    const SizedBox(height: 8),
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.end,
                      children: [
                        const Text(
                          '¥',
                          style: TextStyle(
                            fontSize: 20,
                            color: Colors.white,
                            height: 1.8,
                          ),
                        ),
                        const SizedBox(width: 4),
                        Text(
                          _balance.toStringAsFixed(2),
                          style: const TextStyle(
                            fontSize: 32,
                            fontWeight: FontWeight.w500,
                            color: Colors.white,
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 20),
                    Row(
                      children: [
                        Expanded(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              const Text(
                                '今日收入',
                                style: TextStyle(
                                  fontSize: 12,
                                  color: Colors.white70,
                                ),
                              ),
                              const SizedBox(height: 4),
                              Text(
                                '¥${_todayIncome.toStringAsFixed(2)}',
                                style: const TextStyle(
                                  fontSize: 16,
                                  color: Colors.white,
                                ),
                              ),
                            ],
                          ),
                        ),
                        Container(
                          width: 1,
                          height: 24,
                          color: Colors.white24,
                        ),
                        Expanded(
                          child: Padding(
                            padding: const EdgeInsets.only(left: 20),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                const Text(
                                  '本月收入',
                                  style: TextStyle(
                                    fontSize: 12,
                                    color: Colors.white70,
                                  ),
                                ),
                                const SizedBox(height: 4),
                                Text(
                                  '¥${_monthIncome.toStringAsFixed(2)}',
                                  style: const TextStyle(
                                    fontSize: 16,
                                    color: Colors.white,
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 20),
                    SizedBox(
                      width: double.infinity,
                      child: TextButton(
                        onPressed: _withdraw,
                        style: TextButton.styleFrom(
                          backgroundColor: Colors.white,
                          foregroundColor: const Color(0xFFFF5722),
                          padding: const EdgeInsets.symmetric(vertical: 12),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(8),
                          ),
                        ),
                        child: const Text('提现'),
                      ),
                    ),
                  ],
                ),
              ),
            ),

            // 交易记录标题和查看全部按钮
            SliverPadding(
              padding: const EdgeInsets.fromLTRB(16, 0, 16, 8),
              sliver: SliverToBoxAdapter(
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    const Text(
                      '最近交易',
                      style: TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                    TextButton(
                      onPressed: () {
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (context) => const TransactionListPage(),
                          ),
                        );
                      },
                      style: TextButton.styleFrom(
                        foregroundColor: Colors.grey[600],
                        padding: EdgeInsets.zero,
                        minimumSize: Size.zero,
                        tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                      ),
                      child: Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Text(
                            '查看全部',
                            style: TextStyle(
                              fontSize: 13,
                              color: Colors.grey[600],
                            ),
                          ),
                          Icon(
                            Icons.chevron_right,
                            size: 16,
                            color: Colors.grey[600],
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),

            // 最近交易记录列表（只显示前3条）
            SliverList(
              delegate: SliverChildBuilderDelegate(
                (context, index) {
                  final transaction = _transactions[index];
                  return Container(
                    margin: const EdgeInsets.fromLTRB(16, 0, 16, 12),
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: Material(
                      color: Colors.transparent,
                      child: InkWell(
                        onTap: () {
                          // TODO: 查看交易详情
                        },
                        borderRadius: BorderRadius.circular(8),
                        child: Padding(
                          padding: const EdgeInsets.all(16),
                          child: Row(
                            children: [
                              Container(
                                width: 40,
                                height: 40,
                                decoration: BoxDecoration(
                                  color: transaction['type'] == 'income'
                                      ? const Color(0xFFFF5722).withOpacity(0.1)
                                      : Colors.blue.withOpacity(0.1),
                                  shape: BoxShape.circle,
                                ),
                                child: Icon(
                                  transaction['type'] == 'income'
                                      ? Icons.account_balance_wallet
                                      : Icons.payment,
                                  color: transaction['type'] == 'income'
                                      ? const Color(0xFFFF5722)
                                      : Colors.blue,
                                  size: 20,
                                ),
                              ),
                              const SizedBox(width: 12),
                              Expanded(
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Text(
                                      transaction['title'],
                                      style: const TextStyle(
                                        fontSize: 15,
                                        fontWeight: FontWeight.w500,
                                      ),
                                    ),
                                    const SizedBox(height: 4),
                                    Text(
                                      transaction['time'],
                                      style: TextStyle(
                                        fontSize: 12,
                                        color: Colors.grey[600],
                                      ),
                                    ),
                                    if (transaction['orderId'] != null) ...[
                                      const SizedBox(height: 4),
                                      Text(
                                        '订单号：${transaction['orderId']}',
                                        style: TextStyle(
                                          fontSize: 12,
                                          color: Colors.grey[600],
                                        ),
                                      ),
                                    ],
                                  ],
                                ),
                              ),
                              Text(
                                transaction['type'] == 'income'
                                    ? '+${transaction['amount'].toStringAsFixed(2)}'
                                    : '-${transaction['amount'].toStringAsFixed(2)}',
                                style: TextStyle(
                                  fontSize: 16,
                                  fontWeight: FontWeight.w500,
                                  color: transaction['type'] == 'income'
                                      ? const Color(0xFFFF5722)
                                      : Colors.blue,
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                    ),
                  );
                },
                childCount: _transactions.length > 3 ? 3 : _transactions.length,
              ),
            ),

            // 底部留白
            const SliverPadding(
              padding: EdgeInsets.only(bottom: 16),
            ),
          ],
        ),
      ),
    );
  }
} 